package com.tiantian.quanminxiu.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.shenglian.utils.utils.CommonUtils;
import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMessage;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.constant.WBConstants;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.utils.Utility;
import com.tiantian.quanminxiu.api.AnchorService;
import com.tiantian.quanminxiu.utils.APPUtils;
import com.tiantian.quanminxiu.utils.ApplicationBase;
import com.tiantian.quanminxiu.utils.Constants;
import com.tiantian.quanminxiu.utils.UserData;
import com.tiantian.quanminxiu.utils.sina.AccessTokenKeeper;
import com.tiantian.quanminxiu.utils.sina.UsersAPI;

import org.json.JSONException;
import org.json.JSONObject;

import rx.android.schedulers.AndroidSchedulers;

/**
 * Created by admin on 2016/11/8.
 */
public class Activity_Sina extends Activity implements IWeiboHandler.Response{

    //region 初始化数据
    //分享相关
    private IWeiboShareAPI mWeiboShareAPI;
    public int isLogin = 0;// 判断是登录还是分享 0登录 1分享
    private int roomId;
    private String anchorName;
    private String title;

    //登录相关
    private static SinaBackCall sinaBackCall;
    private AuthInfo mAuthInfo;
    private Oauth2AccessToken mAccessToken;    // 封装"access_token"，"expires_in"，"refresh_token"，并提供了他们的管理功能
    private SsoHandler mSsoHandler;             //注意：SsoHandler 仅当 SDK 支持 SSO 时有效
    private UsersAPI mUsersAPI;
    public String REDIRECT_URL = "http://www.quanminxiu.tv";
    public String SCOPE = "email,direct_messages_read,direct_messages_write,"
                    + "friendships_groups_read,friendships_groups_write,statuses_to_me_read,"
                    + "follow_app_official_microblog," + "invitation_write";
    //endregion

    //region onCreate(Bundle savedInstanceState)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        isLogin = getIntent().getIntExtra("isLogin", 0);
        roomId = getIntent().getIntExtra("roomId", 0);
        anchorName = getIntent().getStringExtra("anchorName");
        title = getIntent().getStringExtra("title");

        if(isLogin==0){
            mAuthInfo = new AuthInfo(this, ApplicationBase.SinaWeibo_Key, REDIRECT_URL,"");
            mSsoHandler = new SsoHandler(this, mAuthInfo);
            mSsoHandler.authorizeClientSso(new AuthListener());
        }else {
            if(roomId<=0){
                CommonUtils.showToask(this,"房间号错误");
                finish();
            }
            shareSina(savedInstanceState);
        }
    }
    //endregion

    //region 分享新浪微博 shareSina(Bundle savedInstanceState)
    public void shareSina(Bundle savedInstanceState){
        mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this, ApplicationBase.SinaWeibo_Key);
        mWeiboShareAPI.registerApp();

        if (savedInstanceState != null) {
            mWeiboShareAPI.handleWeiboResponse(getIntent(), this);
        }

        if (mWeiboShareAPI.isWeiboAppSupportAPI()) {
            int supportApi = mWeiboShareAPI.getWeiboAppSupportAPI();
            ImageLoader.getInstance().loadImage(APPUtils.createUserCover(roomId), new ImageSize(100, 100), new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String imageUri, View view) {

                }

                @Override
                public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                    CommonUtils.showToask(Activity_Sina.this,"图片分享失败，请重试...");
                    finish();
                }

                @Override
                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                    try {
                        Bitmap bitmap = Bitmap.createScaledBitmap(loadedImage, 100, 100, true);
                        loadedImage.recycle();
                        if (supportApi >= 10351 /*ApiUtils.BUILD_INT_VER_2_2*/) {
                            WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
                            TextObject textObject = new TextObject();
                            textObject.text = "你的好友《"+anchorName+"》正在全民秀直播["+title+"]";
                            weiboMessage.textObject = textObject;

                            ImageObject imageObject = new ImageObject();
                            imageObject.setImageObject(bitmap);
                            weiboMessage.imageObject = imageObject;

                            WebpageObject mediaObject = new WebpageObject();
                            mediaObject.identify = Utility.generateGUID();
                            mediaObject.title = "全民秀做全民参与的直播平台~";
                            mediaObject.description = "你的好友《"+anchorName+"》正在全民秀直播["+title+"]";
                            // 设置 Bitmap 类型的图片到视频对象里         设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
                            mediaObject.actionUrl = ApplicationBase.downAppUrl;
                            mediaObject.setThumbImage(bitmap);
                            weiboMessage.mediaObject = mediaObject;

                            SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
                            // 用transaction唯一标识一个请求
                            request.transaction = String.valueOf(System.currentTimeMillis());
                            request.multiMessage = weiboMessage;

                            // 3. 发送请求消息到微博，唤起微博分享界面
                            mWeiboShareAPI.sendRequest(Activity_Sina.this, request);
                        } else {
                            WeiboMessage weiboMessage = new WeiboMessage();
                            WebpageObject mediaObject = new WebpageObject();
                            mediaObject.identify = Utility.generateGUID();
                            mediaObject.title = "全民秀做全民参与的直播平台~";
                            mediaObject.description = "你的好友《"+anchorName+"》正在全民秀直播["+title+"]";
                            // 设置 Bitmap 类型的图片到视频对象里         设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
                            mediaObject.setThumbImage(bitmap);
                            mediaObject.actionUrl = ApplicationBase.downAppUrl;
                            weiboMessage.mediaObject = mediaObject;
                            SendMessageToWeiboRequest request = new SendMessageToWeiboRequest();
                            // 用transaction唯一标识一个请求
                            request.transaction = String.valueOf(System.currentTimeMillis());
                            request.message = weiboMessage;

                            // 3. 发送请求消息到微博，唤起微博分享界面
                            mWeiboShareAPI.sendRequest(Activity_Sina.this, request);
                        }
                    } catch (Exception e) {
                    }

                }

                @Override
                public void onLoadingCancelled(String imageUri, View view) {
                    CommonUtils.showToask(Activity_Sina.this,"图片分享失败，请重试...");
                    finish();
                }
            });

        } else {
            CommonUtils.showToask(this, "微博客户端不支持 SDK 分享或微博客户端未安装或微博客户端是非官方版本。");
            finish();
        }
    }
    //endregion

    //region Activity#onNewIntent
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        // 从当前应用唤起微博并进行分享后，返回到当前应用时，需要在此处调用该函数
        // 来接收微博客户端返回的数据；执行成功，返回 true，并调用
        // {@link IWeiboHandler.Response#onResponse}；失败返回 false，不调用上述回调
        mWeiboShareAPI.handleWeiboResponse(intent, this);
    }
    //endregion

    //region 分享返回接口 onResponse
    @Override
    public void onResponse(BaseResponse baseResp) {
        if(baseResp!= null){
            switch (baseResp.errCode) {
                case WBConstants.ErrorCode.ERR_OK:
                    CommonUtils.showToask(this,"分享成功");
                    ApplicationBase app = ApplicationBase.get(this);
                    AnchorService anchorService = app.getAnchorService();
                    anchorService.share(UserData.Current.mid, Constants.APP_TYPE,UserData.Current.sign,0)
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribeOn(app.defaultSubscribeScheduler())
                            .subscribe(str -> {
                                CommonUtils.showToask(this,str.optString("msg"));
                                UserData.Reload.Fragment_Mine = true;
                                UserData.Base.Coin += 5;
                                finish();
                            }, throwable -> {
                                finish();
                            });
                    break;
                case WBConstants.ErrorCode.ERR_CANCEL:
                    CommonUtils.showToask(this, "分享取消");
                    finish();
                    break;
                case WBConstants.ErrorCode.ERR_FAIL:
                    CommonUtils.showToask(this, "分享失败" + "Error Message: " + baseResp.errMsg);
                    finish();
                    break;
            }
        }
    }
    //endregion

    //region 设置新浪页面返回接口 setSinaBackCall(SinaBackCall backCall)
    static void setSinaBackCall(SinaBackCall backCall){
        sinaBackCall = backCall;
    };
    //endregion

    //region 微博认证授权回调类 AuthListener
    /**
     * 1. SSO 授权时，需要在 {@link #onActivityResult} 中调用 {@link SsoHandler#authorizeCallBack} 后，
     *    该回调才会被执行。
     * 2. 非 SSO 授权时，当授权结束后，该回调就会被执行。
     * 当授权成功后，请保存该 access_token、expires_in、uid 等信息到 SharedPreferences 中。
     */
    class AuthListener implements WeiboAuthListener {

        @Override
        public void onComplete(Bundle values) {
            Log.i("dd","--qqq:onComplete");
            // 从 Bundle 中解析 Token
            mAccessToken = Oauth2AccessToken.parseAccessToken(values);
            //从这里获取用户输入的 电话号码信息
            if (mAccessToken.isSessionValid()) {
                // 保存 Token 到 SharedPreferences
                AccessTokenKeeper.writeAccessToken(Activity_Sina.this, mAccessToken);
                mUsersAPI = new UsersAPI(Activity_Sina.this, ApplicationBase.SinaWeibo_Key, mAccessToken);
                Log.i("dd","--qqq:"+mAccessToken.getUid());
                long uid = Long.parseLong(mAccessToken.getUid());
                mUsersAPI.show(uid, mListener);
            } else {
                // 以下几种情况，您会收到 Code：
                // 1. 当您未在平台上注册的应用程序的包名与签名时；
                // 2. 当您注册的应用程序包名与签名不正确时；
                // 3. 当您在平台上注册的包名和签名与您当前测试的应用的包名和签名不匹配时。
                String code = values.getString("code");
                CommonUtils.showToask(Activity_Sina.this,"授权失败：Obtained the code:"+ code);
                finish();
            }
        }

        @Override
        public void onCancel() {
            CommonUtils.showToask(Activity_Sina.this, "授权取消");
            finish();
        }

        @Override
        public void onWeiboException(WeiboException e) {
            CommonUtils.showToask(Activity_Sina.this, "Auth exception : " + e.getMessage());
            finish();
        }
    }
    //endregion

    //region 当SSO授权Activity退出时，该函数被调用 onActivityResult
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (isLogin==0){
            // SSO 授权回调
            // 重要：发起 SSO 登陆的 Activity 必须重写 onActivityResults
            if (mSsoHandler != null) {
                mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
            }
        }else {
            finish();
        }

    }
    //endregion

    //region 微博 OpenAPI 回调接口 mListener
    private RequestListener mListener = new RequestListener() {
        @Override
        public void onComplete(String response) {
            Log.i("dd","--onComplete:"+response);
            if (!TextUtils.isEmpty(response)) {
                // 调用 User#parse 将JSON串解析成User对象
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String id = jsonObject.optString("id", "");
                    String gender = jsonObject.optString("gender", "");
                    String screen_name   = jsonObject.optString("screen_name", "");
                    String token = mAccessToken.getToken();
                    String expirestime = mAccessToken.getExpiresTime()+"";
                    if(sinaBackCall!=null){
                        sinaBackCall.backcall(id,token,expirestime,screen_name,gender);
                    }else {
                        CommonUtils.showToask(Activity_Sina.this, "微博获取信息错误：缺失SinaBackCall接口");
                    }
                    finish();
                } catch (JSONException e) {
                    e.printStackTrace();
                    finish();
                }
            }else {
                CommonUtils.showToask(Activity_Sina.this, "微博获取信息错误");
                finish();
            }
        }

        @Override
        public void onWeiboException(WeiboException e) {
            Log.i("dd","--onWeiboException:"+e.getMessage());
            CommonUtils.showToask(Activity_Sina.this, "微博获取信息错误：" + e.getMessage());
            finish();
        }
    };
    //endregion

    //region 新浪页面返回接口 SinaBackCall
    public interface SinaBackCall{
        void backcall(String weibo_id, String weibo_token, String weibo_expiresin, String weibo_nickname, String weibo_sex);
    }
    //endregion

}
